import cv2 as cv                  # 导入OpenCV库
import numpy as np                # 导入numpy库
import matplotlib.pyplot as plt   # 导入matplotlib的pyplot库

# 读取图片，0表示灰度图像
img = cv.imread('hanzi1.jpg', 0)
#全局阈值处理
blur = cv.GaussianBlur(img, (5, 5), 0) # 阈值处理的效果受噪声影响较大，常需要先进行滤波等预处理
_, th = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
th1_inv = 255 -th
plt.subplot(2,3,1)
plt.imshow(th1_inv,cmap='gray')
plt.axis('off')

#腐蚀
kernel1 = np.ones((4,4), np.uint8)
eroded_img = cv.erode(th1_inv, kernel1, iterations=4)
plt.subplot(2,3,2)
plt.imshow(eroded_img,cmap='gray')
plt.axis('off')
#膨胀
kernel2 = cv.getStructuringElement(cv.MORPH_CROSS, (4, 4)).astype(np.uint8) 
dilated_img = cv.dilate(eroded_img, kernel2,iterations=8)
plt.subplot(2,3,3)
plt.imshow(dilated_img,cmap='gray')
plt.axis('off')
#闭运算
kernel3 = np.ones((5, 5), np.uint8)
closed_img = cv.morphologyEx(dilated_img, cv.MORPH_CLOSE, kernel3,iterations=25)
plt.subplot(2,3,4)
plt.imshow(closed_img,cmap='gray')
plt.axis('off')
#边缘检测
lower = 50
upper = 200
edges_no_blur = cv.Canny(closed_img, lower, upper)
img_blur = cv.GaussianBlur(edges_no_blur,(3,3), 0) #高斯滤波
edges_with_blur = cv.Canny(img_blur, lower, upper)
plt.subplot(2,3,5)
plt.imshow(edges_with_blur,cmap='gray')
plt.axis('off')
#轮廓检测
contours, _ = cv.findContours(edges_with_blur, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
img_copy = img.copy()
for c in contours:
    perimeter = cv.arcLength(c, True)
    print("轮廓周长：", perimeter)
    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    if perimeter > 100:
        cv.rectangle(img_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)
plt.subplot(2,3,6)
plt.imshow(img_copy,cmap='gray')
plt.axis('off')
plt.show()